package com.kjsdfgk.hjmdsf.ftmztlist.mvp.presenter;

import android.app.Application;
import android.os.Handler;

import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.jess.arms.utils.RxLifecycleUtils;
import com.kjsdfgk.hjmdsf.app.App;
import com.kjsdfgk.hjmdsf.app.entity.Account;
import com.kjsdfgk.hjmdsf.app.entity.WebPhoto;
import com.kjsdfgk.hjmdsf.app.utils.SharedPrefsUtils;
import com.kjsdfgk.hjmdsf.ftmztlist.mvp.contract.MZTListContract;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Element;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/07/2020 22:13
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class MZTListPresenter extends BasePresenter<MZTListContract.Model, MZTListContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public MZTListPresenter(MZTListContract.Model model, MZTListContract.View rootView) {
        super(model, rootView);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
    int page = 1;

    public void loadImages(int p , String tag) {
//        {"主页", "最热", "推荐", "性感妹子", "日本妹子", "台湾妹子", "清纯妹子"};
        page = p;
        mModel.loadIndexImg(tag ,page++)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading(new Date().toString()))
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();
                        if (e.getMessage().contains("404")){
                            SharedPrefsUtils.setInt(tag , 1);
                            mRootView.showMessage("无更多数据 ，请下拉刷新");
                        } else {

                            mRootView.showMessage(e.toString());
                        }


                    }

                    @Override
                    public void onNext(@NonNull String result) {
                        mRootView.hideLoading();
                        mRootView.showWebPhoto(parseJPG(result ,tag));

                    }
                });
    }

    public void loadImagesMore(String tag) {
        mModel.loadIndexImg(tag ,page++)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading(new Date().toString()))
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {
                        mRootView.hideLoading();
                        if (e.getMessage().contains("404")){
                            SharedPrefsUtils.setInt(tag , 1);
                            mRootView.showMessage("无更多数据");
                        }else {
                            mRootView.showMessage(e.toString());
                        }

                    }

                    @Override
                    public void onNext(@NonNull String result) {
                        mRootView.hideLoading();
                        mRootView.showWebPhotoMore(parseJPG(result , tag));
                        SharedPrefsUtils.setInt(tag , page-1);
                    }
                });
    }


    private  List<WebPhoto> parseJPG(String result , String tag) {
        try {
//            Jsoup.parse(result).select("img").get(28).attributes().asList().get(0).getValue();
            List<WebPhoto> photoList = new ArrayList<>();
            for (Element element : Jsoup.parse(result).select("img")){
                if (element.parent().attributes().html().contains("target=\"_blank\"")&&element.parent().attributes().html().contains("href")){
                    WebPhoto webPhoto = new WebPhoto();
                    for (Attribute attribute:element.parent().attributes().asList()){
                        if ("href".equals(attribute.getKey())){
                            webPhoto.href = attribute.getValue();
                            for (Attribute a:element.attributes().asList()){
                                if ("src".equals(a.getKey())){
                                    webPhoto.url = a.getValue();
                                }
                                if ("alt".equals(a.getKey())){
                                    webPhoto.alt = a.getValue();
                                    String s = a.getValue();
                                    StringBuilder sb = new StringBuilder(s);
                                    sb.reverse();
                                    StringBuilder stringBuilder = new StringBuilder(sb.substring(sb.indexOf("]")+1 ,sb.indexOf("[")));
                                    webPhoto.imgNum =Integer.parseInt(stringBuilder.reverse().toString());
                                    webPhoto.category = tag;
                                }
                            }
                            photoList.add(webPhoto);
                        }
                    }



                }

            }
           return photoList;
        }catch (Exception e){
            mRootView.showMessage(e.toString());
        }
        return null;
    }

    public void downloadServerData(String tag ,final int mypage) {


        mModel.loadIndexImg(tag ,mypage+1)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onNext(@NonNull String result) {

                        List<WebPhoto> list = (parseJPG(result ,tag));
                        for (WebPhoto p:list) {
                            p.save();
                        }
                        SharedPrefsUtils.setInt(tag , mypage + 1);
//                        mRootView.saveAndgoNext(mypage);

                    }
                });
    }

    public Account getAccount() {
        return (Account) ((App)mApplication).getAppComponent().extras().get("Account");
    }
}
